package com.tmp.alarm.task;

import com.tmp.alarm.utils.MySQLUtils;
import com.tmp.alarm.utils.PropertiesUtil;
import com.tmp.alarm.utils.SendMessagesUtils;
import com.tmp.alarm.utils.UUIDByDateUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 *依据job耗时的时间来告警
 */
public class JobSpendTimeAlarm {

    private  final  static  Logger LOGGER = LoggerFactory.getLogger(JobSpendTimeAlarm.class);
    private  final  static  String processing_type = PropertiesUtil.get("processing_type").trim();
    private  final  static  String final_type = PropertiesUtil.get("final_type").trim();
    private  final  static  String last_alarm_task = PropertiesUtil.get("last_alarm_task").trim();
    private  final  static  int job_spend_time_limit = Integer.parseInt(PropertiesUtil.get("job_spend_time_limit").trim());
    private  final  static  int job_spend_time_alarm_limit = Integer.parseInt(PropertiesUtil.get("job_spend_time_alarm_limit").trim());
    private  final  static  String alarm_list = PropertiesUtil.get("alarm_phone_list").trim();
    private  final  static  String alarm_title = "job超时告警";

    /**
     * 统计正在运行的job所耗费的时间,即是mart_mobile_job_info表中的
     * log_time减去start_time时间超过配置文件中指定的时间则算该job超时
     */
    public static  void  countJobSpendTime(){

        LOGGER.info("进入了countJobSpendTime**************************");

        String sql = "";
        if(last_alarm_task.equals("JobSpendTimeAlarm")){
            //是最后一个就要获取分组后的最大的id,以便于update type=final_type
            sql = "SELECT m.id,m.type,m.log_time,m.start_time,m.job_id FROM mart_mobile_job_info AS m WHERE m.type="+processing_type+" GROUP BY job_id ORDER BY id DESC";
        }else{
            //不是最后一个task就不需要order by 了这样增加点效率
            sql = "SELECT m.id,m.type,m.log_time,m.start_time,m.job_id FROM mart_mobile_job_info AS m WHERE m.type="+processing_type+" GROUP BY job_id";
        }

        Connection connection = null;
        ResultSet rs = null;
        String maxId = "";
        try {
            connection = MySQLUtils.getConnection();
            rs  = MySQLUtils.query(connection,sql);

            rs.next();
            int rows = rs.getRow();
            if(rows >0){
                maxId  = rs.getString("id");
                rs.beforeFirst();
                //将查询过的数据置为不可用,这是目前最后一个指标
                if(StringUtils.isNotEmpty(maxId)){
                    String update_sql = "UPDATE mart_mobile_job_info SET type="+final_type+" WHERE id<="+maxId;
                    MySQLUtils.executeUpdate(connection,update_sql);
                }
                String alarmContentResult = "";
                while (rs.next()){
                    String job_id = rs.getString("job_id");
                    String log_time = rs.getString("log_time");
                    log_time = log_time.trim();
                    if(log_time.length()<14){
                        log_time = log_time+"00";
                    }
                    String start_time = rs.getString("start_time");
                    String res = "";
                    res = dealJobTimesAlarm(log_time,start_time,job_id);
                    if(StringUtils.isNotEmpty(res) && res.length()>0){
                      alarmContentResult = alarmContentResult+"【"+res+"】;";
                    }
                }
                if (StringUtils.isNotEmpty(alarmContentResult) && alarmContentResult.length()>0){
                    alarmContentResult = alarmContentResult.substring(0,alarmContentResult.lastIndexOf(";"));
                    String flag = SendMessagesUtils.sendMessagesToPhone(alarm_list,alarm_title,alarmContentResult);
                    if(flag.equals("1")){
                        LOGGER.info("job超时告警发送短信success  "+alarmContentResult);
                    }else{
                        LOGGER.error("job告警发送短信失败!!!!!  "+alarmContentResult);
                    }
                }

            }else {
                LOGGER.info("本次job超时判断没有查询到满足条件数据...");
            }

            MySQLUtils.returnConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException("判断比较运行job是否超时异常..."+e.getMessage());
        }
    }

    /**
     * 判断job执行时间是否超时,并且告警
     * @param log_time
     * @param start_time
     */
    private static String  dealJobTimesAlarm(String log_time,String start_time,String job_id){

        String format = "yyyyMMddHHmmss";
        long logTimes = UUIDByDateUtils.geSelfTimes(format,log_time.trim());
        long startTimes = UUIDByDateUtils.geSelfTimes(format,start_time.trim());

        long exeTimes = (logTimes-startTimes)/1000;
        String alarmContentResult = null;
        if(exeTimes > job_spend_time_limit){

            //执行超时了得判断该job_id之前是否告警过,不能总是一直告警
            //查询job_spend_time_alarm表,job_id相等的倒叙排序取第一个即可,
            // 查不到就告警,并且记录,查到依据alarm_time与配置中的job_spend_time_alarm_limit对比,大于则再一次告警,不大于就不告警
            try {
                Connection connection =  MySQLUtils.getConnection();
                String sql = "SELECT j.id,j.job_id,j.alarm_time FROM job_spend_time_alarm j WHERE j.job_id='"+job_id+"' ORDER BY id DESC LIMIT 1";
                ResultSet rs = MySQLUtils.query(connection,sql);
                rs.next();
                int rows = rs.getRow();
                String current_alarm_time = UUIDByDateUtils.getCurrentTimes("yyyyMMddHHmmss");
                if(rows >0){
                    LOGGER.info("job_id:"+job_id+" 已经告警过...");
                    String alarm_time = rs.getString("alarm_time");
                    long  before_at  = UUIDByDateUtils.geSelfTimes("yyyyMMddHHmmss",alarm_time);//上次告警时间
                    long now_at = UUIDByDateUtils.geSelfTimes("yyyyMMddHHmmss",current_alarm_time);//本次告警时间
                    long cur_limit = now_at-before_at;
                    long self_limit = job_spend_time_alarm_limit*1000;//用户自定义的间隔时间
                    if(cur_limit>self_limit){
                        LOGGER.info("job_id==="+job_id+"  再一次超时将告警,并保存记录到job_spend_time_alarm中...");
                        String alarm_content = "job_id为:"+job_id+"  执行超时:"+exeTimes+"s,告警多次";
                        alarmContentResult = alarm_content;
                        LOGGER.info("job再一次超时告警  "+alarm_content);
                        String addSql = "INSERT INTO job_spend_time_alarm(job_id,alarm_time,alarm_limit_time,log_time,start_time) VALUES('"+job_id+"',"+current_alarm_time+","+job_spend_time_limit+","+log_time+","+start_time+")";
                        MySQLUtils.executeUpdate(connection,addSql);

                       /* String flag = SendMessagesUtils.sendMessagesToPhone(alarm_list,alarm_title,alarm_content);
                        if(flag.equals("1")){

                        }else{LOGGER.info("job再一次超时告警success  "+alarm_content);
                            String addSql = "INSERT INTO job_spend_time_alarm(job_id,alarm_time,alarm_limit_time,log_time,start_time) VALUES('"+job_id+"',"+current_alarm_time+","+job_spend_time_limit+","+log_time+","+start_time+")";
                            MySQLUtils.executeUpdate(connection,addSql);
                            LOGGER.error("job再一次告警失败!!!!!  "+alarm_content);
                        }*/
                    }else{
                        LOGGER.info("job_id为:"+job_id+"  已经告警了,同一个job_id上次告警距离当前还没有超过指定的间隔时间");
                    }
                }else{
                    LOGGER.info("job_id==="+job_id+"  首次超时将告警,并保存记录到job_spend_time_alarm中...");
                    String alarm_content = "job_id为:"+job_id+"  执行超时:"+exeTimes+"s";
                    alarmContentResult = alarm_content;
                    LOGGER.info("job超时告警  "+alarm_content);
                    String addSql = "INSERT INTO job_spend_time_alarm(job_id,alarm_time,alarm_limit_time,log_time,start_time) VALUES('"+job_id+"',"+current_alarm_time+","+job_spend_time_limit+","+log_time+","+start_time+")";
                    MySQLUtils.executeUpdate(connection,addSql);

                    /*String flag = SendMessagesUtils.sendMessagesToPhone(alarm_list,alarm_title,alarm_content);
                    if(flag.equals("1")){
                        LOGGER.info("job超时告警success  "+alarm_content);
                        String addSql = "INSERT INTO job_spend_time_alarm(job_id,alarm_time,alarm_limit_time,log_time,start_time) VALUES('"+job_id+"',"+current_alarm_time+","+job_spend_time_limit+","+log_time+","+start_time+")";
                        MySQLUtils.executeUpdate(connection,addSql);
                    }else{
                        LOGGER.error("job告警失败!!!!!  "+alarm_content);
                    }*/
                }
                MySQLUtils.returnConnection(connection);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("job耗时判断异常..."+e.getMessage());
            }
        }
        /*else{
            LOGGER.info("job_id==="+job_id+"   没有超时,不告警...");
        }*/
        return alarmContentResult;
    }

}
































